package com.liwy3.lark;

import com.liwy3.YQException;
import com.liwy3.YQHttp;
import com.liwy3.YQJsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class LarkExcel {

    private Map<String, String> appTokenMap = new ConcurrentHashMap<>();
    private static final String prefixAppAccessToken = "https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal";
    private static final String prefixUrl = "https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/";
    private static final String suffixUrl = "?valueRenderOption=FormattedValue";

    public static String getExcelUrl(String excelId, String sheetId, String startCell, String endCell) {

        String range = sheetId + "!" + startCell + ":" + endCell;
        String url = prefixUrl + excelId + "/values/" + range + suffixUrl;
        log.info("飞书excel的url为{}", url);
        return url;
    }

    public String getAppAccessToken(String appId, String appSecret) {

        String cacheKey = "lark-" + appId + ":" + appSecret;
        String appAccessToken = appTokenMap.get(cacheKey);
        //如果token过期
        if (StringUtils.isBlank(appAccessToken)) {

            Map<String, String> map = new HashMap();
            map.put("app_id", appId);
            map.put("app_secret", appSecret);

            YQHttp.Response post = YQHttp.newRequest()
                    .setRequestConfig(YQHttp.RC_60)
                    .setUrl(prefixAppAccessToken)
                    .setPostBody(YQJsonUtils.toJson(map))
                    .json();
            Map contentMap = YQJsonUtils.toObject(post.getContent(), Map.class);
            log.info("查询飞书app_access_token返回结果{}", contentMap);
            if ("0".equals(String.valueOf(contentMap.get("code")))) {
                appAccessToken = YQJsonUtils.convert(contentMap.get("app_access_token"), String.class);
                appTokenMap.put(cacheKey, appAccessToken);
            } else {
                throw new YQException(400, "获取飞书access_token失败:" + YQJsonUtils.toJson(contentMap));
            }
        }
        return appAccessToken;
    }

    public List<List<String>> getExcelValueList(String appAccessToken, String excelId, String sheetId, String startCell, String endCell) {

        String url = getExcelUrl(excelId, sheetId, startCell, endCell);
        YQHttp.Response get = YQHttp.newRequest()
                .setRequestConfig(YQHttp.RC_60)
                .setUrl(url)
                .addHeader("Authorization", "Bearer " + appAccessToken)
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .get();
        Map contentMap = YQJsonUtils.toObject(get.getContent(), Map.class);
        log.info("查询飞书excel单元格内容返回结果{}", contentMap);
        if ("0".equals(String.valueOf(contentMap.get("code")))) {
            Map data = YQJsonUtils.convert(contentMap.get("data"), Map.class);
            Map valueRange = YQJsonUtils.convert(data.get("valueRange"), Map.class);
            List values = YQJsonUtils.convert(valueRange.get("values"), List.class);
            List<List<String>> resultValues = new ArrayList<>();
            for (Object object : values) {
                List<String> resultValue = new ArrayList<>();
                if (object != null) {
                    List value = YQJsonUtils.convert(object, List.class);
                    if (value != null) {
                        for (Object o : value) {
                            resultValue.add(o == null ? "" : String.valueOf(o));
                        }
                    }
                }
                resultValues.add(resultValue);
            }
            return resultValues;
        } else {
            throw new YQException(400, "获取飞书excel数据失败:" + YQJsonUtils.toJson(contentMap));
        }
    }

    public String getExcelValue(String appAccessToken, String excelId, String sheetId, String cell) {

        String url = getExcelUrl(excelId, sheetId, cell, cell);
        YQHttp.Response get = YQHttp.newRequest()
                .setRequestConfig(YQHttp.RC_60)
                .setUrl(url)
                .addHeader("Authorization", "Bearer " + appAccessToken)
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .get();
        Map contentMap = YQJsonUtils.toObject(get.getContent(), Map.class);
        log.info("查询飞书excel单元格内容返回结果{}", contentMap);
        if ("0".equals(String.valueOf(contentMap.get("code")))) {
            Map data = YQJsonUtils.convert(contentMap.get("data"), Map.class);
            Map valueRange = YQJsonUtils.convert(data.get("valueRange"), Map.class);
            List values = YQJsonUtils.convert(valueRange.get("values"), List.class);
            if (CollectionUtils.isNotEmpty(values)) {
                List<String> value = YQJsonUtils.convert(values.get(0), List.class);
                if (CollectionUtils.isNotEmpty(value)) {
                    return value.get(0) == null ? null : String.valueOf(value.get(0));
                }
            }
            return null;
        } else {
            throw new YQException(400, "获取飞书excel数据失败:" + YQJsonUtils.toJson(contentMap));
        }
    }


}
